import React, { useState, useEffect, useRef } from 'react';
import { Graph } from '@antv/x6';
import { Popover, Button } from 'antd';

interface EdgeContextMenuProps {
  graph: Graph;
}

const EdgeContextMenu: React.FC<EdgeContextMenuProps> = ({ graph }) => {
  const [visible, setVisible] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [currentEdge, setCurrentEdge] = useState<Graph.Edge | null>(null);
  const popoverRef = useRef<HTMLDivElement>(null);
  const clickTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    const handleEdgeContextMenu = (args: {
      e: MouseEvent;
      edge: Graph.Edge;
    }) => {
      args.e.preventDefault();
      args.e.stopPropagation();

      // 获取边的位置信息
      const pos = graph.clientToGraph(args.e.clientX, args.e.clientY);
      setPosition(pos);
      setCurrentEdge(args.edge);
      setVisible(true);
    };

    const handleBlankClick = () => {
      setVisible(false);
    };

    // 注册事件监听
    graph.on('edge:contextmenu', handleEdgeContextMenu);
    graph.on('blank:click', handleBlankClick);

    // 点击外部关闭菜单
    const handleClickOutside = (event: MouseEvent) => {
      if (clickTimeoutRef.current) {
        clearTimeout(clickTimeoutRef.current);
      }
      clickTimeoutRef.current = setTimeout(() => {
        if (popoverRef.current && !popoverRef.current.contains(event.target as Node)) {
          setVisible(false);
        }
      }, 100);
    };

    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      // 清理事件监听
      graph.off('edge:contextmenu', handleEdgeContextMenu);
      graph.off('blank:click', handleBlankClick);
      document.removeEventListener('mousedown', handleClickOutside);
      if (clickTimeoutRef.current) {
        clearTimeout(clickTimeoutRef.current);
      }
    };
  }, [graph]);

  const handleDelete = () => {
    if (currentEdge) {
      graph.removeEdge(currentEdge.id);
    }
    setVisible(false);
  };

  const handleEdit = () => {
    if (currentEdge) {
      // 实现编辑逻辑，例如：
      graph.startEdgeEdit(currentEdge);
    }
    setVisible(false);
  };

  // 转换为页面坐标
  const clientPosition = graph.localToPage(position.x, position.y);
  const popoverStyle: React.CSSProperties = {
    position: 'absolute',
    left: `${clientPosition.x + 10}px`,
    top: `${clientPosition.y + 10}px`,
  };

  return (
    <div ref={popoverRef} style={popoverStyle}>
      <Popover
        open={visible}
        content={
          <div>
            <Button type="text" block onClick={handleDelete}>
              删除边
            </Button>
            <Button type="text" block onClick={handleEdit}>
              编辑边
            </Button>
            {/* 可以添加更多菜单项 */}
          </div>
        }
      >
        <div style={{ display: 'none' }} />
      </Popover>
    </div>
  );
};

export default EdgeContextMenu;